#pragma once

#ifdef SAMSUNG_VERSION
#include <string.h>
#else
#include <memory.h>	// memcpy declaration
#endif

class COutputBuffer
{
	short *m_channelBuffers[2], *m_remainderBuffer, *m_buffer;		// 2 channels maximum
	int remainder_pos;
	bool m_originalBuffer[2];
	short m_channels;
	unsigned short m_remainder;
	size_t m_bufferSize, m_currentSize;

public:
	COutputBuffer(short channels) : m_channels(channels), m_remainder(0)
	{
		m_remainderBuffer = new short[8*1024];	// 8 Kb
		remainder_pos = 0;
	};

	~COutputBuffer() { delete[] m_remainderBuffer; };

	int init(void *buffer,size_t bufferSize)
	{
		m_bufferSize = bufferSize;
		m_buffer = (short*)buffer;
		int rem_size = 0;
		if (m_remainder)
		{
			rem_size = m_remainder;
			if ( bufferSize < m_remainder )
			{
				rem_size = bufferSize;
			}
			memcpy( m_buffer, m_remainderBuffer + remainder_pos, rem_size*sizeof(short) );
			m_currentSize = rem_size;
			m_remainder -= rem_size;
			remainder_pos += rem_size;

			if ( m_remainder > 0 )
				return -1;

			remainder_pos = 0;
		}
		else
			m_currentSize = 0;

		for (short i = 0; i < m_channels; i++)
		{
			m_channelBuffers[i] = m_buffer + m_currentSize + i;
			m_originalBuffer[i] = true;
		}

		return rem_size;
	}

#pragma warning(disable:4018)
	void append(short channel,short value)
	{
		if (m_originalBuffer[channel])
		{
			if ((m_channelBuffers[channel] - m_buffer) >= m_bufferSize)
			{
				m_channelBuffers[channel] = m_remainderBuffer + channel;
				m_originalBuffer[channel] = false;
				m_remainder++;
			}
			else
				m_currentSize++;
		}
		else
			m_remainder++;

		*m_channelBuffers[channel] = value;
		m_channelBuffers[channel] += m_channels;
	}

	size_t size() const { return m_currentSize; };
};
